﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System;

namespace WebApiOrm.Provider
{
    public class DefaultOrmFactory : IOrmFactory
    {
        private readonly IServiceProvider serviceProvider;
        private readonly IOptions<OrmFactoryOptions> options;

        public DefaultOrmFactory(
            IServiceProvider serviceProvider,
            IOptions<OrmFactoryOptions> options)
        {
            this.serviceProvider = serviceProvider;
            this.options = options;
        }

        public IOrmProvider Create(string ormName)
        {
            if (this.options.Value.TryGetProviderType(ormName, out var providerType) == false)
            {
                throw new InvalidOperationException($"未注册的Orm名称{ormName}");
            }
            return (IOrmProvider)this.serviceProvider.GetRequiredService(providerType);
        }
    }
}
